package org.future.task.redis.cluster;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.Set;

public class ClusterFactory {

    public ClusterFactory(Set<HostAndPort> hostAndPorts) {
        this.hostAndPorts = hostAndPorts;
    }

    private Set<HostAndPort> hostAndPorts;

    private GenericObjectPoolConfig genericObjectPoolConfig;

    private int connectionTimeout = 60000;

    private int soTimeout = 1000;

    private int maxAttempts = 10;

    private String password;

    public GenericObjectPoolConfig getGenericObjectPoolConfig() {
        return genericObjectPoolConfig;
    }

    public ClusterFactory setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) {
        this.genericObjectPoolConfig = genericObjectPoolConfig;
        return this;
    }

    public int getConnectionTimeout() {
        return connectionTimeout;
    }

    public ClusterFactory setConnectionTimeout(int connectionTimeout) {
        if (connectionTimeout > 0)
            this.connectionTimeout = connectionTimeout;
        return this;
    }

    public int getSoTimeout() {
        return soTimeout;
    }

    public ClusterFactory setSoTimeout(int soTimeout) {
        if (soTimeout > 0)
            this.soTimeout = soTimeout;
        return this;
    }

    public int getMaxAttempts() {
        return maxAttempts;
    }

    public ClusterFactory setMaxAttempts(int maxAttempts) {
        if (maxAttempts > 0)
            this.maxAttempts = maxAttempts;
        return this;
    }

    public String getPassword() {
        return password;
    }

    public ClusterFactory setPassword(String password) {
        this.password = password;
        return this;
    }

    public JedisCluster builder() {
        JedisCluster jedisCluster;
        if (genericObjectPoolConfig == null) {
            genericObjectPoolConfig = new GenericObjectPoolConfig();
            genericObjectPoolConfig.setMaxIdle(100);
            genericObjectPoolConfig.setMaxTotal(100);
            genericObjectPoolConfig.setMinIdle(10);
        }
        if (password == null || "".equals(password)) {
            jedisCluster = new JedisCluster(hostAndPorts, 60000, 1000, 10, genericObjectPoolConfig);
        } else {
            jedisCluster = new JedisCluster(hostAndPorts, 60000, 1000, 10, password, genericObjectPoolConfig);
        }
        return jedisCluster;
    }
}
